import React from 'react';
import { Table, Input, Button, Popconfirm, Form, Row, Col, InputNumber, Select, } from 'antd';
import { connect } from 'dva';
import FormItem from 'antd/lib/form/FormItem';

const { Option } = Select
const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class FreeTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '选择地区',
        dataIndex: 'place',
        key: 'place',
        render: (text, record, i) => 
        <a onClick={this.changeModalStuaus.bind(this, i)}>
          {props.trans.freeCity || record.districtNames ? props.trans.freeCity || record.districtNames : '点击选择地区'}
        </a>,
      },
      {
        title: '设置包邮条件',
        dataIndex: 'setIsFree',
        key: 'setIsFree',
        render: (t, r, i) => <Row type='flex'>
          <Col>
            <Select 
              defaultValue={r.transConditon} 
              onChange={this.selectFreeCondition.bind(this, i)} 
              style={{width: 200}}
            >
              <Option value={'0'}>件数</Option>
              <Option value={'1'}>金额</Option>
              <Option value={'2'}>件数 + 金额</Option>
            </Select>
          </Col>
          <Col>满</Col>
          <Col>
            <Input 
              onChange={(e) => this.handleFreeNum(e.target.value, i)}
              defaultValue={r.fullAmount}
            />
          </Col>
          <Col>件 包邮</Col>
        </Row>
      },
    ]

    this.state = {
      dataSource: [],
      count: 0,
      params: {},
    };
  }

  selectFreeCondition = (index, val) => {
    const { freeParams, freeRecord } = this.props.trans
    const newData = [...freeRecord]
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      transConditon: val,
    });
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        freeRecord: newData,
      }
    })
  }

  handleFreeNum = (e, i) => {
    const { freeParams, freeRecord } = this.props.trans
    const newData = [...freeRecord]
    const item = newData[i];
    newData.splice(i, 1, {
      ...item,
      fullAmount: e,
      fullMoney: 0,
    });
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        freeRecord: newData,
      }
    })
  }

  changeModalStuaus = (i) => {
    const { trans } = this.props
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        freeModal: !trans.freeModal,
      }
    })
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        current: i
      }
    })
  }

  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter((item, index) => index !== key) }, () => {
      dispatch({
        type: 'trans/update',
        payload: {
          freeRecord: this.state.dataSource,
        }
      })
    });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const { dispatch } = this.props
    const newData = {
      key: count,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
    dispatch({
      type: 'trans/update',
      payload: {
        freeRecord: [...dataSource, newData]
      }
    })
  };

  handleSave = row => {
    const { dispatch } = this.props
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
    dispatch({
      type: 'trans/update',
      payload: {
        freeRecord: newData
      }
    })
  };

  handleParams = (param, val) => {
    this.state.params[param] =  val

    this.setState({params: this.state.params}, () => {
      this.props.dispatch({
        type: 'trans/update',
        payload: {
          params: {
            ...this.state.params
          }
        }
      })
    })
  }

  render() {
    const { dataSource } = this.state;
    const { isEdit } = this.props
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Row>
        <Button type="primary" onClick={this.handleAdd}>新增</Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource.length == 0 ? isEdit.frees : dataSource}
          columns={columns}
          rowKey={r => r.id || r.key}
        />
      </Row>
    );
  }
}

export default connect(({ trans }) => ({
  trans,
}))(FreeTable)